import { createWebHistory, createRouter } from "vue-router";
import { getUserInfoApi } from "../api/index";
import Message from "../utils/Message";
import HomeView from "../views/HomeView.vue";
import LoginView from "../views/LoginView.vue";
import RegisterView from "../views/RegisterView.vue";
import RecycleView from "../views/Recycle.vue";
import ShareView from "../views/ShareView.vue";
import SettingView from "../views/SettingView.vue";
import AdminView from "../views/AdminView.vue";
import { useStore } from "../stores/index";

const routes = [
  { path: "/", redirect: "/login" },
  {
    path: "/home/:parentId?",
    component: HomeView,
    name: "home",
    meta: { requiresAuth: true },
  },
  {
    path: "/login",
    component: LoginView,
    name: "login",
    meta: { requiresAuth: false },
  },
  {
    path: "/register",
    component: RegisterView,
    name: "register",
    meta: { requiresAuth: false },
  },
  {
    path: "/share/:shareId?",
    component: ShareView,
    name: "share",
    meta: { requiresAuth: false },
  },
  {
    path: "/recycle",
    component: RecycleView,
    name: "rerecycle",
    meta: { requiresAuth: true },
  },
  {
    path: "/setting",
    component: SettingView,
    name: "setting",
    meta: { requiresAuth: true },
  },
  {
    path: "/admin",
    component: AdminView,
    name: "admin",
    meta: { requiresAuth: true },
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

router.beforeEach(async (to, from, next) => {
  const store = useStore();

  try {
    // 如果有 token 但没有用户信息，尝试自动登录
    if (localStorage.getItem("token") && !store.userInfo) {
      const res = await getUserInfoApi();
      localStorage.setItem("token", res.token);
      store.userInfo = res.user;
      store.userInfo.avatar = `${import.meta.env.VITE_BASE_URL}api/user/avatar/${res.user.id}?timestamp=${Date.now()}`;
      Message.success("欢迎回来");

      if (to.name === "login" || to.name === "register") {
        return next("/home");
      }
    }
    // 如果有 token 和用户信息，尝试自动刷新
    else if (localStorage.getItem("token") && store.userInfo) {
      try {
        const res = await getUserInfoApi();
        localStorage.setItem("token", res.token);
        store.userInfo = res.user;
        store.userInfo.avatar = `${import.meta.env.VITE_BASE_URL}api/user/avatar/${res.user.id}?timestamp=${Date.now()}`;
      } catch (error) {
        console.error("刷新用户信息失败:", error);
        localStorage.removeItem("token");
        store.userInfo = null;
      }
    }

    // 检查是否需要登录
    if ((!localStorage.getItem("token") || !store.userInfo) && to.meta.requiresAuth) {
      const query = new URLSearchParams({
        redirect: to.fullPath,
        from: "app",
        mode: "redirect",
      });
      return next(`/login?${query.toString()}`);
    }

    // 所有检查通过，继续导航
    next();
  } catch (error) {
    console.error("认证失败:", error);
    localStorage.removeItem("token");
    store.userInfo = null;

    const query = new URLSearchParams({
      redirect: to.fullPath,
      from: "app",
      mode: "redirect",
    });
    return next(`/login?${query.toString()}`);
  }
});

export default router;
